package com.renchunlin.taobaounion.ui.fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.renchunlin.taobaounion.R;
import com.renchunlin.taobaounion.base.BaseFragment;
import com.renchunlin.taobaounion.model.domain.Categories;
import com.renchunlin.taobaounion.presenter.impl.HomePresenterImpl;
import com.renchunlin.taobaounion.ui.adapter.HomePagerAdapter;
import com.renchunlin.taobaounion.view.IHomeCallback;

import java.util.logging.Handler;

import butterknife.BindView;

public class HomeFragment extends BaseFragment implements IHomeCallback {

    private HomePresenterImpl homePresenter;
    @BindView(R.id.home_indicator)
    public TabLayout mTabLayout;

    @BindView(R.id.home_pager)
    public ViewPager homePage;
    private HomePagerAdapter homePagerAdapter;

    @Override
    protected int getRootViewResId() {
        return R.layout.fragment_home;
    }

    @Override
    protected View loadRootView(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.base_home_fragment_layout, container, false);
    }

    @Override
    protected void initView(View rootView) {
        mTabLayout.setupWithViewPager(homePage);
        //给ViewPager设置适配器
        homePagerAdapter = new HomePagerAdapter(getChildFragmentManager());
        //设置适配器
        homePage.setAdapter(homePagerAdapter);
    }

    @Override
    protected void initPresenter() {
        //创建Presenter
        homePresenter = new HomePresenterImpl();
        homePresenter.registerCallback(this);
    }

    @Override
    protected void loadData() {
        //加载数据
        homePresenter.getCategories();
    }

    //IHomeCallback 回调 start
    @Override
    public void onCategoriesLoaded(Categories categories) {
        //加载数据成功的页面
        setUpState(State.SUCCESS);
        //加载的数据就会从这里回来
        if (homePagerAdapter != null) {
            homePagerAdapter.setCategories(categories);
        }
    }

    @Override
    public void onNetworkError() {
        setUpState(State.ERROR);
    }

    @Override
    public void onLoading() {
        //开始去加载页面
        setUpState(State.LOADING);
    }

    @Override
    public void onEmpty() {
        setUpState(State.EMPTY);
    }
    //IHomeCallback 回调 end

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        release();
    }

    @Override
    protected void release() {
        //取消回调注册
        if (homePresenter != null) {
            homePresenter.unregisterCallback(this);
        }
    }

    //复写父类网络重试方法
    @Override
    protected void onRetryClick() {
        //重新加载分类内容
        if (homePresenter != null) {
            homePresenter.getCategories();
        }
    }
}
